import { Dispatch } from 'redux';
import { Types, ResultProps } from './types.d'
import { AxiosResponse } from 'axios'
import { FetchAddItem, FetchDeleteItem, FetchEditItem, FetchQueryList } from 'api/index'

export const Actions = {
  initQueryList(data: any[]) {
    return {
      type: Types.FETCH_QUERY_LIST,
      payload: data
    }
  },
  // 查询接口 // 返回函数{  }  async 之后，返回了promise
  getQueryList() {
    return async (dispatch:Dispatch) => {
      const res:AxiosResponse<ResultProps> = await FetchQueryList()
      const { data, code, msg } = res.data;
      data.forEach((v, i) => {
        v.key = v.id
      })
      dispatch(this.initQueryList(data))
    }
  },
  initAddItem(data:any[]) {
    return {
      type: Types.FETCH_ADD_ITEM,
      payload: data
    }
  },
  // 添加接口
  getAddItem(data:any) {
    return async (dispatch:Dispatch ) => {
      const res:AxiosResponse<ResultProps> = await FetchAddItem(data)
      console.log('res::', res)
      dispatch(this.initAddItem(res.data.data))
    }
  },
  initUpdateItem(data:any) {
    return {
      type: Types.FETCH_UPDATE_ITEM,
      payload: data
    }
  },
  // 更新接口
  getUpdateItem(data: any) {
    return async (dispatch:Dispatch ) => {
      const res:AxiosResponse<ResultProps> = await FetchEditItem(data)
      dispatch(this.initUpdateItem(res.data.data))
    }
  },
  initDelteItem(data:any) {
    return {
      type: Types.FETCH_DELTE_ITEM,
      payload: data
    }
  },
  // 删除接口
  getDelteItem(params: any) {
    return async (dispatch: Dispatch) => {
      const res:AxiosResponse<ResultProps> = await FetchDeleteItem(params)
      dispatch(this.initDelteItem(res.data.data))
    }
  },
  updateTableStatus() {
    return {
      type: Types.UPDATE_TABLE_STATUS,
    }
  }
}


/**
 * dispatch({ type: '', payload: data })
 *
 * diaptch(Actions.getQueryList())
 *
 * thunk可以让action从对象变为了一个函数。参数是dispatch
 *
 *
 */

